<template>
  <scroll-view
    :scroll-y="true"
    :style="{ height: windowHeight + 'px' }"
    :scrollTop="scrollTop"
    :enable-flex="true"
  >
    <view class="home-container">
      <!-- 搜索区域 -->

      <div class="info-container">
        <view class="card station-info">
          <view class="title">川开微网系统改造充电站</view>
          <view class="station-address">
            <view class="icon">
              <u-icon name="map-fill" size="24px" class="icon-local"></u-icon>
            </view>
            <view class="address">
              四川省成都市双流区黄甲街道川开电气有限公司中汉太阳能聚光光伏产业园
            </view>
          </view>
        </view>
        <view class="card station-info-2">
          <view class="title">电站信息</view>
          <view class="info-item">
            <view class="info-item-label">营业时间</view>
            <view class="info-item-text">周一至周日00:00-24:00</view>
          </view>
          <view class="info-item">
            <view class="info-item-label">服务提供 </view>
            <view class="info-item-text">川开电气</view>
          </view>
          <view class="info-item">
            <view class="info-item-label">客服热线</view>
            <view class="info-item-text">400300001</view>
          </view>
        </view>
        <view class="pile-statistics">
          <view class="pile-statistics-item" @click="handleViewPile(1)">
            <view class="item-type">快</view>
            <view class="item-info">
              <text class="item-info-left">
                空闲{{ pileStatisticInfo.q.unUsedNumber || 0 }}
              </text>
              <text class="item-info-right">
                /共{{ pileStatisticInfo.q.number || 0 }}
              </text>
            </view>
          </view>
          <view class="pile-statistics-item" @click="handleViewPile(2)">
            <view class="item-type item-type-slow">慢</view>
            <view class="item-info">
              <text class="item-info-left">
                空闲{{ pileStatisticInfo.s.unUsedNumber || 0 }}
              </text>
              <text class="item-info-right">
                /共{{ pileStatisticInfo.s.number || 0 }}
              </text>
            </view>
          </view>
        </view>
      </div>

      <!-- 电价信息、充电桩 -->

      <view class="card plie-container main-content-container">
        <view class="type-tab">
          <u-tabs
            :list="[{ name: '价格' }, { name: '终端' }]"
            :activeStyle="{ color: 'rgba(40, 42, 49, 1)', fontWeight: 'bold' }"
            :inactiveStyle="{ color: 'rgba(126, 127, 131, 1)' }"
            lineColor="rgba(17, 143, 67, 1)"
            @change="handleTabChange"
          ></u-tabs>
        </view>
        <div id="price" class="content-section-card">
          <view class="terminal-title">电价信息</view>
          <PriceInfo :price-data="stationInfo"></PriceInfo>
        </div>

        <view id="terminal" class="content-section-card">
          <!-- 终端内容 -->
          <view class="terminal-title">终端信息</view>
          <view class="u-page__tag-item">
            <u-tag
              v-for="(item, index) in radios"
              :key="index"
              :text="item.name"
              :plain="!item.checked"
              type="warning"
              :name="item.name"
              @click="radioClick"
              shape="circle"
              :bgColor="
                item.checked ? 'rgba(17, 143, 67, 1)' : 'rgba(218, 234, 223, 1)'
              "
              :borderColor="
                item.checked
                  ? 'rgba(128, 151, 135, 1)'
                  : 'rgba(128, 151, 135, 1)'
              "
              :color="item.checked ? '#fff' : 'rgba(128, 151, 135, 1)'"
              class="tag-item"
            >
            </u-tag>
          </view>
          <view
            class="scroll-item"
            v-for="pile in filteredPileList"
            :key="pile.EquipmentID"
          >
            <view class="pile-status-wrapper">
              <view
                :class="
                  pile.ConnectorInfos[0].Status !== '空闲'
                    ? 'pile-status--active'
                    : ''
                "
                class="pile-status"
              >
                {{
                  pile.ConnectorInfos[0].Status === "空闲" ? "空闲" : "已插枪"
                }}
              </view>
              <view class="time-info" v-if="pile.status === 1">13:04插枪</view>
            </view>

            <view class="pile-rect" @click="handlePileClick(pile)">
              <view class="plie-header">
                <view class="pile-title">
                  <text class="name">
                    {{ pile.EquipmentName }}
                  </text>
                  <text class="code" v-if="false">
                    ({{ pile.EquipmentID }})
                  </text>
                </view>
                <view
                  class="pile-type"
                  :class="
                    pile?.ConnectorInfos[0]?.ConnectorType === 3
                      ? 'pile-type-slow'
                      : ''
                  "
                  >{{ pile?.ConnectorInfos[0]?.ConnectorSpeed?.slice(0, 1) }}
                </view>
              </view>

              <view class="pile-car-info">
                <text class="text">终端编号 </text>
                <text class="text">{{ pile.EquipmentID }}</text>
              </view>
              <view class="pile-type-info">
                <text>
                  {{ pile?.EquipmentType === 1 ? "直流快充" : "交流单相7kW" }} |
                  国标2011 国标2015
                </text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 导航栏 -->
      <tabbar></tabbar>
    </view>
  </scroll-view>
</template>

<script setup>
import { onShow } from "@dcloudio/uni-app";
import { ref, reactive, computed, onMounted } from "vue";
// import { requestStations, requestPiles } from "@/utils/api/charge.js";
import {
  fetchStationInfo,
  fetchPileList,
  getOrderListByOpenId,
} from "@/utils/api/teld.js";

import { GET_IS_BIND_TIP, SET_IS_BIND_TIP } from "@/utils/token.js";
import { getUserRoleInfo } from "@/utils/api/user.js";
import PriceInfo from "../../components/pirce-info/PriceInfo.vue";
import useUserStore from "@/store/user.js";
import usePileStore from "@/store/pile.js";

let userStore = useUserStore();
const pileStore = usePileStore();
// let loading = ref(false);

const scrollTop = ref(0);

let kw = ref("");
let timer = ref(null);
let windowHeight = ref(0);

const elTop = reactive({
  price: 0,
  terminal: 0,
});
const stationInfo = ref({});
let pileList = ref([]);
// let pageSize = ref(10);
// let pageNo = ref(1);
// let total = ref(0);
let currentTab = ref("价格");
const radios = reactive([
  { checked: false, name: "全部" },
  { checked: false, name: "空闲" },
  { checked: false, name: "已插枪" },
]);

const radioClick = (name) => {
  console.log("name:", name);
  // const currentRadio = radios.find((item) => item.name === name);
  // currentRadio.checked = true;
  radios.forEach((item) => {
    item.checked = item.name === name;
  });
};
const filteredPileList = computed(() => {
  const currentPlieFilterStatus =
    radios.find((item) => item.checked)?.name || "";
  if (currentPlieFilterStatus) {
    console.log(
      "curcurrentPlieFilterStatusrentPlieFilterStatus:",
      currentPlieFilterStatus
    );

    if (currentPlieFilterStatus === "空闲") {
      return pileList.value.filter((item) => {
        return item.ConnectorInfos[0]?.Status === currentPlieFilterStatus;
      });
    } else if (currentPlieFilterStatus === "已插枪") {
      return pileList.value.filter((item) => {
        return item.ConnectorInfos[0]?.Status !== "空闲";
      });
    } else {
      return pileList.value;
    }
  }
  return pileList.value;
});
const pileStatisticInfo = computed(() => {
  const quick = pileList.value.filter(
    (item) => item?.ConnectorInfos[0]?.ConnectorType === 4
  );
  const slow = pileList.value.filter(
    (item) => item?.ConnectorInfos[0]?.ConnectorType === 3
  );
  return {
    q: {
      number: quick.length,
      unUsedNumber: quick.filter(
        (item) => item?.ConnectorInfos[0].Status === "空闲"
      ).length,
    },
    s: {
      number: slow.length,
      unUsedNumber: slow.filter(
        (item) => item?.ConnectorInfos[0].Status === "空闲"
      ).length,
    },
  };
});

onShow(() => {
  uni.hideTabBar({
    animation: false,
  });
  userStore.activeTab = 0;

  let sysInfo = uni.getWindowInfo();
  console.log("sysInfo:", sysInfo);

  windowHeight.value = sysInfo.windowHeight;
  // 获取充电站信息
  getStationInfo();
  //获取充电站信息
  getPileList();
  fetchUserRoleInfo();
  console.log("showen:");
});

onMounted(() => {
  console.log("mounted:");

  initScrollTopCache();
  judgeOrderStatus();
  showBindTip();
});

/**
 * 根据订单信息判断是否有未支付订单
 */
const judgeOrderStatus = async () => {
  const list = await fetchOrderList();
  if (list.length > 0) {
    const unpayOrder = list.find((item) => item.payStatus === 0);

    if (unpayOrder) {
      uni.showModal({
        title: "提示",
        content: "您有未支付订单，请先支付",
        showCancel: false,
        confirmText: "去支付",
        success(res) {
          if (res.confirm) {
            uni.navigateTo({
              url: `/pages/order/detail?outTradeNo=${unpayOrder.outTradeNo}`,
            });
          }
        },
      });
    }
  }
};
/**
 * 获取当前用户信息根据用户角色判断电价等
 */
const fetchUserRoleInfo = () => {
  const data = {
    openId: userStore.openid,
  };

  return getUserRoleInfo(data).then((res) => {
    console.log("res-user:", res);
    if (res) {
      userStore.userRoleInfo = res;
    }
    return res;
  });
};
/**
 * 提示当前用户是否已知晓绑定后会享受折扣
 */
const showBindTip = () => {
  const isBindTip = GET_IS_BIND_TIP();
  if (isBindTip) {
    return;
  }
  uni.showModal({
    title: "温馨提示",
    content: `如果您是内部员工，绑定工号后可享受员工折扣，可前往"我的-编辑"页面中进行绑定`,
    confirmText: "我已知晓",
    cancelText: "访客模式",
    success(res) {
      // if (res.confirm) {
      //   // 点击了"我已知晓"
      //   userStore.isBindTip = true;
      // } else if (res.cancel) {
      //   // 点击了"访客模式"
      //   userStore.isBindTip = false;
      // }
      SET_IS_BIND_TIP(true);
    },
    fail() {
      console.log("fail:");
    },
  });
};

/**
 * 获取订单列表
 * @returns {Promise<order[]>}
 */
const fetchOrderList = () => {
  const data = {
    openId: userStore.openid,
    payStatus: "", // 整形数字，0：未支付， 1：已支付，全部查询填：null
  };
  // console.log("orderParams:", data);

  return getOrderListByOpenId(data).then((res) => {
    // console.log("res:", res);
    return res;
  });
};

// 初始化 scrollTop 位置
const initScrollTopCache = () => {
  // 获取 scroll-view 的引用
  const query = wx.createSelectorQuery();
  query
    .select(`#price`)
    .boundingClientRect((rect) => {
      elTop.price = rect.top; // 更新 scrollTop 的值
    })
    .select(`#terminal`)
    .boundingClientRect((rect) => {
      elTop.terminal = rect.top; // 更新 scrollTop 的值
    })
    .exec();
};

const getStationInfo = () => {
  // console.log("fetch-station:");
  fetchStationInfo().then((res) => {
    stationInfo.value = res;
  });
};
//搜索站点
let handleInput = (keyword) => {
  if (kw.value !== keyword) {
    kw.value = keyword;
    //清除timer对应的定时器
    clearTimeout(timer.value);
    //重启一个延时器，并把timerid赋值给timer
    timer.value = setTimeout(() => {
      // 对关键词进行解码
      let decodedKeyword = decodeURIComponent(keyword);
      //根据关键词，查询搜索建议列表
      getPileList({ params: { name: decodedKeyword } });
    }, 600);
  }
};
//获取充电站数据
let getPileList = () => {
  const data = {
    StationsInfo: {
      LastQueryTime: "",
      PageNo: 1,
      PageSize: 50,
    },
    StationStatus: {
      StationIDs: ["5101161213"],
    },
  };
  fetchPileList(data).then((res) => {
    pileList.value = res;
  });
  // 显示加载中状态
  // loading.value = true;
  // loading.value = false;
  // getAuthOfLocation();
};
const getAuthOfLocation = () => {
  uni.authorize({
    scope: "scope.userLocation",
    success() {
      stationList.value = [];
      //授权成功，获取位置
      uni.getLocation({
        type: "wgs84",
        timeout: 10000, // 设置10秒超时
        success: function (res) {
          console.log("res:", res);

          //成功获取经纬度，拼接后给到接口里的位置字段
          // stationInfo.coordinate = res.longitude + "," + res.latitude;
          // getHasStations().then();
        },
        fail: function () {
          // getHasStations().then();
          // uni.$showMsg("请授权地理位置权限");
          // 再次调用getStationList进行再次授权
        },
      });
    },
  });
};

const handlePileClick = (pile) => {
  pileStore.updatePile(pile);
  // console.log("pile:", pile);

  uni.navigateTo({
    url: `/pages/pile/pile?id=${pile.EquipmentID}`,
  });
};

/**
 * 跳转充电桩列表
 * @param type
 */
const handleViewPile = (type) => {
  uni.navigateTo({
    url: `/pages/pile/list?type=${type}`,
  });
};
// 终端/价格 tab 切换函数
const handleTabChange = (tabItem) => {
  currentTab.value = tabItem.name;
  // if (tabItem.name === "价格") {
  //   nextTick(() => {
  //     // scrollIntoView.value = "price";
  //     scrollTop.value = 350;
  //   });
  // } else if (tabItem.name === "终端") {
  //   nextTick(() => {
  //     scrollTop.value = 515;
  //     // scrollIntoView.value = "terminal";
  //   });
  // }
  let key = "price";
  if (tabItem.name === "价格") {
    key = "price";
  } else if (tabItem.name === "终端") {
    key = "terminal";
  }
  scrollTop.value = elTop[key] - 50; // 更新 scrollTop 的值
  // const query = wx.createSelectorQuery();
  // query
  //   .select(`#${key}`)
  //   .boundingClientRect((rect) => {
  //     console.log("rect:", rect);
  //     scrollTop.value = rect.top - 50; // 更新 scrollTop 的值
  //   })
  //   .exec();
};
</script>

<style lang="scss">
@import "../../style/common.scss";

.u-page__tag-item {
  display: flex;
  align-items: center;
  // justify-content: space-around;
  margin-right: 20px;
  .active {
    background-color: rgba(17, 143, 67, 1);
    border-color: rgba(128, 151, 135, 1);
    color: #fff;
  }
  view + view {
    margin-left: 18px;
  }
}
.home-container {
  box-sizing: border-box;
  background-color: rgb(227, 230, 233);
  width: 100vw;
  min-height: 100vh;
  padding-top: 12px;
  // padding-left: 16px;
  // padding-right: 16px;
  padding-bottom: 0;
  .station-info {
    padding: 18px 8px;
    .title {
      font-weight: bold;
      font-size: 20px;
      color: $color-dark;
    }
    .station-address {
      display: flex;
      align-items: center;
      flex-wrap: nowrap;
      margin-top: 8px;
      .icon {
        width: 20px;
        height: 20px;
        margin-right: 20px;
        .icon-local {
          color: #cc2b2b;
        }
      }
      .address {
        font-size: 14px;
        color: $color-primary;
      }
    }
  }
  .station-info-2 {
    margin-top: 8px;
    margin-bottom: 8px;
    .title {
      font-weight: bold;
      font-size: 16px;
      color: #282a31;
      line-height: 24px;
      text-align: left;
      font-style: normal;
      text-transform: none;
    }
    .info-item {
      display: flex;
      margin-top: 10px;
      .info-item-label {
        font-weight: 400;
        font-size: 14px;
        color: #7e7f83;
        margin-right: 20px;
      }
      .info-item-text {
        font-weight: 400;
        font-size: 14px;
        color: #200e32;
      }
    }
  }
  .info-container {
    padding: 0 16px;
  }
  .pile-statistics {
    display: flex;
    justify-content: space-between;
    margin-top: 8px;
    margin-bottom: 8px;
    .pile-statistics-item {
      flex: 1;
      height: 48px;
      background-color: #ffffff;
      border-radius: 10px;
      display: flex;
      justify-content: space-around;
      align-items: center;
      & + .pile-statistics-item {
        margin-left: 8px;
      }
      .item-type {
        width: 24px;
        height: 24px;
        color: #ffffff;
        font-size: 16px;
        background: #cc2b2b;
        border-radius: 2px 2px 2px 2px;
        text-align: center;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .item-type-slow {
        background: #2bcc30;
      }
      .item-info {
        .item-info-left {
          color: $color-dark;
          font-size: 16px;
        }
        .item-info-right {
          color: $color-light;
          font-size: 14px;
        }
      }
    }
    // .pile-statistics-item {
    //   display: flex;
    //   .item-type {
    //     font-size: 16rpx;
    //     background: #cc2b2b;
    //     border-radius: 2px 2px 2px 2px;
    //   }
    // }
  }
  .search-box {
    position: sticky;
    top: 0;
    z-index: 999;
    background-color: #0aa671;
    .mini-btn {
      height: 36px;
      line-height: 36px;
      border-radius: 15px;
      margin: 25rpx;
    }
  }
  .plie-container {
    padding: 18px 8px;

    // .price-info {
    //   .price-row {
    //     display: flex;
    //     align-items: baseline;
    //     justify-content: space-between;
    //     margin-top: 10px;
    //     .price-item {
    //       font-size: 14px;
    //       color: $color-primary;
    //       .number {
    //         color: $color-red;
    //         font-size: 18px;
    //         font-weight: bold;
    //       }
    //       .unit {
    //         font-size: 12px;
    //         color: $color-light;
    //       }
    //     }
    //   }
    // }
    #terminal {
      margin-top: 16px;
    }
    .terminal-title {
      font-size: 14px;
      color: #282a31;
      margin-bottom: 12px;
      font-weight: bold;
    }
  }
  .main-content-container {
    // margin: 0 -16px;
    background-color: rgb(245, 246, 248);
    padding: 4px 16px 20px;
    border-radius: 16px 16px 0 0;
    .type-tab {
      display: flex;
      align-self: center;
      justify-content: center;
      position: sticky;
      top: 0;
      will-change: position;
      background-color: rgb(245, 246, 248);
      z-index: 9;
      padding-bottom: 4px;
    }
    .content-section-card {
      background-color: #ffffff;
      padding: 16px 7px;
      border-radius: 12px 12px 12px 12px;
      -webkit-border-radius: 12px 12px 12px 12px;
      -moz-border-radius: 12px 12px 12px 12px;
      -ms-border-radius: 12px 12px 12px 12px;
      -o-border-radius: 12px 12px 12px 12px;
      width: 100%;
      box-sizing: border-box;
    }
  }

  .scroll-item {
    // background-color: #ffffff;
    padding: 15px 0 15px 20px;
    padding-right: 0;
    font-size: 20rpx;
    // margin-bottom: 20rpx;
    // border-radius: 15rpx;
    border-bottom: 1px solid rgba(234, 234, 234, 1);
    display: flex;
    align-items: center;
    // justify-content: space-between;
    .pile-status-wrapper {
      // display: flex;
      // flex-direction: column;
      // align-items: center;
      // justify-content: center;
      // margin-right: 20px;
      .pile-status {
        width: 52px;
        height: 52px;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 4px solid #24cea6;
        border-radius: 50%;
        color: #24cea6;

        &--active {
          border-color: rgba(97, 167, 247, 1);
          color: rgba(97, 167, 247, 1);
        }
      }
      .time-info {
        text-align: center;
        margin-top: 8px;
        font-size: 12px;
        color: #b4b5b7;
      }
    }

    .pile-tanan {
      font-size: 30rpx;
      text-align: center;
      color: #0aa671;
    }
    .plie-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .pile-rect {
      flex: 1;
    }
    .pile-title {
      font-size: 25rpx;
      font-weight: bold;
      .name {
        font-size: 16px;
      }
      .code {
        font-size: 12px;
      }
    }
    .pile-type {
      width: 24px;
      height: 24px;
      color: #ffffff;
      font-size: 16px;
      background: #cc2b2b;
      border-radius: 2px 2px 2px 2px;
      text-align: center;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .pile-type-slow {
      background: #2bcc30;
    }
    .pile-car-info {
      display: inline-block;
      padding: 2px 3px;
      margin: 6px 0;
      background-color: rgba(240, 240, 240, 1);
      font-size: 12px;
      .text {
        color: rgba(180, 181, 183, 1);
      }
    }
    .pile-type-info {
      font-size: 14px;
      color: rgba(126, 127, 131, 1);
    }
    .pile-box {
      margin: 10rpx 0;
      display: flex;
      justify-content: space-between;
      .price {
        display: flex;
        align-items: center;
        .pri {
          font-size: 30rpx;
          color: #0aa671;
          margin: 0 10rpx;
        }
        .limit {
          color: #adadb3;
          font-size: 20rpx;
        }
      }
      .resi {
        display: flex;
        font-size: 25rpx;
        .fast {
          width: 30rpx;
          height: 30rpx;
        }
        .free {
          font-weight: bold;
          margin: 0 10rpx;
        }
      }
    }
    .pile-distance {
      display: flex;
      align-items: center;
      .distance {
        font-size: 25rpx;
      }
      .navi {
        margin-left: 20rpx;

        .location {
          width: 40rpx;
          height: 40rpx;
        }
      }
    }
  }
  // loding区域
  .loading {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    flex-direction: column;
    align-items: center;
    .loading-icon {
      width: 100px;
      height: 100px;
      margin-bottom: 10px;
    }
    .loading-text {
      font-size: 14px;
      color: #999;
    }
  }
}
</style>
